import sys
import os

py_path = os.path.abspath(__file__)
proto_path = os.path.join(os.path.dirname(os.path.dirname(py_path)), 'proto')
msg_path = os.path.join(os.path.dirname(os.path.dirname(py_path)), 'src', 'encode_pack', 'msg_rec_reflect.erl')
hrl_path = os.path.join(os.path.dirname(os.path.dirname(py_path)), 'include', 'mod_info.hrl')

proto_src = {}


def scan_file(path):
    f = open(path, 'r', encoding='utf-8')
    global proto_src
    for line in f.readlines():
        if line.startswith("// "):
            proto_info = line.split()
            proto_src[proto_info[2]] = proto_info[1]
    f.close()


def make_hrl():
    text = []
    head = u"""-ifndef(__MOD_INFO_H__).
-define(__MOD_INFO_H__, true).
"""
    global proto_src
    text.append(head)
    for k,v in proto_src.items():
        line = u"-define(%s, %s)." % (k, v)
        text.append(line)
    text.append(u"\n-endif.")
    with open(hrl_path, 'w', encoding='utf-8') as fp:
        fp.write("\n".join(text))
        fp.close()


def make_erl():
    text = []
    head = u"""-module(msg_rec_reflect).
-author("admin").
-include("mod_info.hrl").
-export([rec_name/1, send_name/1, msg_id/1, pb_mod/1]).
"""
    global proto_src
    text.append(head)
    for k,v in proto_src.items():
        if k.startswith("c2s"):
            line = u"rec_name(?%s)->%s;" % (k, k)
            text.append(line)
    text.append(u"rec_name(_)->undef.\n\n")
    for k,v in proto_src.items():
        if k.startswith("s2c"):
            line = u"send_name(?%s)->%s;" % (k, k)
            text.append(line)
    text.append(u"send_name(_)->undef.\n\n")
    for k,v in proto_src.items():
        line = u"msg_id(%s)->?%s;" % (k, k)
        text.append(line)
    text.append(u"msg_id(_)->undef.\n\n")
    pb = u"""pb_mod(1) -> system_pb;
pb_mod(_) -> system_pb."""
    text.append(pb)
    with open(msg_path, 'w', encoding='utf-8') as fp:
        fp.write("\n".join(text))
        fp.close()


print(py_path)
print(proto_path)
print(msg_path)
print(hrl_path)
for root, dirs, files in os.walk(proto_path):
    for name in files:
        top_name, extra = os.path.splitext(name)
        if extra == '.proto':
            scan_file(os.path.join(proto_path, name))
make_hrl()
make_erl()

